<template>
  <div class="login-wrapper">
    <div class="modal">
      <el-form ref="userForm" :model="user" status-icon :rules="rules">
        <div class="title">后台管理系统</div>
        <el-tabs v-model="mod" class="demo-tabs" @tab-click="handleModClick">
          <el-tab-pane label="密码登录" name="pwd">
            <el-form-item prop="phone" >
              <el-input type="text" v-model="user.phone" placeholder="手机号"/>
            </el-form-item>
            <el-form-item prop="pwd">
              <el-input type="password" v-model="user.pwd" placeholder="密码"/>
            </el-form-item>
            <el-form-item prop="code" >
              <el-input v-model="user.code" placeholder="验证码">
                <template #suffix>
                  <img :src="imgCaptchaSrc" @click="refreshImgCaptcha" style="width:120px;height:36px;">
                </template>
              </el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="短信登录" name="sms">
            <el-form-item prop="phone" >
              <el-input type="text" v-model="user.phone"
                        show-word-limit maxlength="11"
                        @change = "phoneChange" placeholder="手机号"/>
            </el-form-item>
            <el-form-item prop="code" >
              <el-input v-model="user.code" placeholder="验证码">
                <template #suffix>
                  <el-button type="default" :disabled="btnSmsDisabled" @click.native="refreshSmsCaptcha">
                    {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
        <el-form-item style="padding-top:50px;">
          <el-button type="primary" class="btn-login" @click="login">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref,getCurrentInstance,reactive,onMounted} from 'vue'
const {proxy} = getCurrentInstance()
//
const imgCaptchaSrc = ref('');
onMounted(()=>{
  // console.log('加载完成')
  refreshImgCaptcha();
})

//账号
const user = ref({
  phone:'admin',
  pwd:'123456',
  code:'',
  uuid:'',
})

const mod = ref('pwd');
const countdown = ref(0);
const btnSmsDisabled = ref(true);
const rules = reactive({
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'}
  ],
  pwd: [
    {required: true, message: '请输入密码', trigger: 'blur'}
  ],
  code: [
    {required: true, message: '请输入验证码', trigger: 'blur'}
  ],
  uuid: [
    {required: true, message: '请输入刷新验证码', trigger: 'blur'}
  ],
});

//刷新图片验证码
const refreshImgCaptcha = () => {
  // console.log('刷新验证码',proxy.$api)
  proxy.$api.getImgCaptcha(user.value.uuid).then((res)=>{
    // console.log(res)
    if(res.code === 200){
      imgCaptchaSrc.value = 'data:image/png;base64,'+res.data.img;
      user.value.uuid = res.data.uuid;
    }
  });
}
//手机号输入改变
const phoneChange = (v)=>{
  countdown.value = 0;
  const reg = /^1\d{10}$/
  if (reg.test(v)) {
    btnSmsDisabled.value = false;
  }else{
    btnSmsDisabled.value = true;
  }
}
//发送短信验证码
const refreshSmsCaptcha = ()=>{
  if(user.value.phone.length != 11 || user.value.phone.charAt(0) != '1'){
    return proxy.$message.error('手机号不可用');
  }
  btnSmsDisabled.value = true;
  proxy.$api.getSmsCaptcha(user.value.phone,user.value.uuid).then((res)=>{
    // console.log(res)
    if(res.code === 200){
      user.value.uuid = res.data.uuid;
      countdown.value = 60;
      let timer = setInterval(() => {
        if (countdown.value > 1) {
          countdown.value -= 1;
        } else {
          clearInterval(timer);
          timer = null;
          btnSmsDisabled.value = false;
        }
      }, 1000);
    }
  });
}
//切换登录方式
const handleModClick = (v)=>{
  // console.log(v.paneName);
  mod.value = v.paneName
}
//登录
const login = () =>{
  proxy.$refs.userForm.validate((valid)=>{
    if (valid) {
      if(mod.value === 'pwd'){
        proxy.$api.pwdLogin(user.value).then((res)=>{
          if(res.code === 200){
            proxy.$message.success(res.msg);
            localStorage.setItem(res.data.key,res.data.token);
            localStorage.setItem('token_key',res.data.key);
            localStorage.setItem('user_id',res.data.user_id);
            proxy.$router.push('/welcome')
          }else{
            proxy.$message.error(res.msg);
          }
        })
      }else if(mod.value === 'sms'){
        proxy.$api.smsLogin(user.value).then((res)=>{
          if(res.code === 200){
            proxy.$message.success(res.msg);
            localStorage.setItem(res.data.key,res.data.token);
            localStorage.setItem('token_key',res.data.key);
            localStorage.setItem('user_id',res.data.user_id);
            proxy.$router.push('/welcome')
          }else{
            proxy.$message.error(res.msg);
          }
        })
      }
    } else {
      return false
    }
  })
}
</script>

<style lang="scss">
.login-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f9fcff;
  height: 98vh;
  background-image: url("../assets/imgs/welcome.png");
  background-repeat: no-repeat;
  .modal {
    width: 500px;
    padding: 50px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0px 0px 10px 3px #c7c9cb4d;
    .title {
      font-size: 50px;
      line-height: 1.5;
      text-align: center;
      margin-bottom: 30px;
    }
    .btn-login {
      width: 100%;
    }
  }

}
</style>
